package com.weipai.springboot.module.service.impl;

import com.weipai.springboot.enums.RetCode;
import com.weipai.springboot.model.ProductCategory;
import com.weipai.springboot.model.ProductProperty;
import com.weipai.springboot.model.api.Response;
import com.weipai.springboot.model.api.Tree;
import com.weipai.springboot.module.dao.ProductCategoryDao;
import com.weipai.springboot.module.dao.ProductPropertyDao;
import com.weipai.springboot.module.service.ProductCategoryService;
import com.weipai.springboot.module.util.TreeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 曹朋飞
 * @Date: 2018/08/02 14:29
 * <p>
 * 商品类别
 */
@Service
public class PeoductCategoryServiceImpl implements ProductCategoryService {

    private static final Logger log = LoggerFactory.getLogger(PeoductCategoryServiceImpl.class);

    @Autowired
    ProductCategoryDao productCategoryDao;
    @Autowired
    ProductPropertyDao productPropertyDao;

    //保存
    @Override
    public Response save(ProductCategory productCategory) {
        Response response = new Response();
        Map<String, Object> map = new HashMap<>();
        String parentId = productCategory.getParentId();
        if (!StringUtils.isEmpty(productCategory.getParentId()) && !"null".equals(productCategory.getParentId())) {
            List<Map<String, Object>> productCategoryByPid = productCategoryDao.getProductCategoryByPid(productCategory.getParentId());
            for (int i = 0; i < productCategoryByPid.size(); i++) {
                String productCategoryName = (String) productCategoryByPid.get(i).get("name");
                if (productCategory.getProductCategoryName().equals(productCategoryName)) {
                    map.put("status", 401);
                    map.put("msg", "此分类已存在，请重新输入");
                    response.setData(map);
                    return response;
                }
            }
        } else {
            map.put("status", 401);
            map.put("msg", "请传入上级id,如为顶级请传0");
            response.setData(map);
            return response;
        }


        //拼接path
        if (!StringUtils.isEmpty(productCategory.getParentId()) && !"null".equals(productCategory.getParentId())) {
            //有上级
            String path = null;
            if (parentId == null || StringUtils.isEmpty(parentId) || "null".equals(parentId) || "0".equals(parentId)) {
                path = productCategory.getProductCategoryId();
            } else {
                ProductCategory parent = productCategoryDao.getProductCategoryById(parentId);
                path = parent.getPath() + "," + productCategory.getProductCategoryId();
            }
            productCategory.setPath(path);
        } else {
            //顶级目录
            productCategory.setPath(productCategory.getProductCategoryId());
        }
        if (1 == productCategoryDao.insert(productCategory)) {
            response.setCode(RetCode.SUCCESS);
        } else {
            log.debug("保存货品类别失败:{}", productCategory.getProductCategoryName());
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //修改
    @Override
    public Response update(ProductCategory productCategory) {
        Response response = new Response();
        Map<String, Object> map = new HashMap<>();
        ProductCategory productCategoryById = productCategoryDao.getProductCategoryById(productCategory.getProductCategoryId());
        if (!StringUtils.isEmpty(productCategoryById.getParentId()) && !"null".equals(productCategoryById.getParentId())) {
            List<Map<String, Object>> productCategoryByPid = productCategoryDao.getProductCategoryByPid(productCategoryById.getParentId());
            for (int i = 0; i < productCategoryByPid.size(); i++) {
                String productCategoryName = (String) productCategoryByPid.get(i).get("name");
                if (productCategory.getProductCategoryName().equals(productCategoryName)) {
                    map.put("status", 401);
                    map.put("msg", "此分类已存在，请重新输入");
                    response.setData(map);
                    return response;
                }
            }
        } else {
            map.put("status", 401);
            map.put("msg", "请传入上级id,如为顶级请传0");
            response.setData(map);
            return response;
        }
        if (1 == productCategoryDao.updateByPrimaryKey(productCategory)) {
            response.setCode(RetCode.SUCCESS);
        } else {
            log.debug("保存货品类别失败:{}", productCategory.getProductCategoryName());
            response.setCode(RetCode.REQUEST_ERROR);
        }
        response.setData(map);
        return response;
    }

    //查询商品类别详情
    @Override
    public Response getProductCategoryById(String id) {
        Response response = new Response();
        Map<String, Object> map = new HashMap<>();
        ProductCategory productCategory = productCategoryDao.getProductCategoryById(id);
        if (null != productCategory) {
            response.setCode(RetCode.SUCCESS);
            response.setData(map);
        } else {
            response.setCode(RetCode.NO_DATA);
        }
        return response;
    }

    //查询顶级分类/一级分类/二级分类的--分页列表
    @Override
    public List<ProductCategory> selectAllByRankDel(int del, String rank, String sort, String way, String id) {
        return productCategoryDao.selectAllByRankDel(del, rank, sort, way, id);
    }

    //更改商品类别的状态---禁用还是启用
    @Override
    public Response changeStatus(String id, Integer status) {
        Response response = new Response();
        Map<String, Object> map = new HashMap<>();
        ProductCategory productCategory = productCategoryDao.getProductCategoryById(id);
        if (null != productCategory) {
            if (status == -1) {
                //查看此分类下面是否还有有效的分类--统计数量
                Integer count = productCategoryDao.getValidChildCountById(id);
                if (count > 0) {
                    map.put("msg", "请删除下级分类");
                    response.setCode(RetCode.REQUEST_ERROR);
                    response.setData(map);
                    return response;
                }
                //查看是否有关联的商品
                Integer productCount = productCategoryDao.getProductId(id);
                if (productCount > 0) {
                    map.put("msg", "请删除关联产品");
                    response.setCode(RetCode.REQUEST_ERROR);
                    response.setData(map);
                    return response;
                }
            }
            if (1 == productCategoryDao.updateStatus(id, status)) {
                response.setCode(RetCode.SUCCESS);
            } else {
                response.setCode(RetCode.REQUEST_ERROR);
            }
        } else {
            response.setCode(RetCode.NO_DATA);
        }
        return response;
    }

    //查看此分类下面是否还有有效的分类--统计数量
    private Integer getValidChildCountById(String id) {
        return productCategoryDao.getValidChildCountById(id);
    }

    //批量删除
    @Override
    public Response batchDeleteById(String[] id) {
        Response response = new Response();
        Map<String, Object> map = new HashMap<>();
        for (int i = 0; i < id.length; i++) {
            //查看此分类下面是否还有有效的分类--统计数量
            if (getValidChildCountById(id[i]) > 0) {
                map.put("status", 401);
                map.put("msg", "请删除下级分类");
                response.setData(map);
                return response;
            }
            //查看是否有关联的商品
            Integer productCount = productCategoryDao.getProductId(id[i]);
            if (productCount > 0) {
                map.put("msg", "请删除关联产品");
                response.setCode(RetCode.REQUEST_ERROR);
                response.setData(map);
                return response;
            }
        }
        if (productCategoryDao.batchDeleteById(id) > 0) {
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //查询三级分类
    @Override
    public Response getAllProductCategory() {
        Response response = new Response();
        List<ProductCategory> productCategories = productCategoryDao.getAllProductCategory();
        List<Tree> list = new ArrayList<>();

        for (ProductCategory productCategory : productCategories) {
            Tree tree = new Tree();
            tree.setName(productCategory.getProductCategoryName());
            tree.setId(productCategory.getProductCategoryId());
            tree.setpId(productCategory.getParentId());
            tree.setCategoryRank(productCategory.getProductCategoryRank());
            tree.setImg(productCategory.getProductCategoryImg());
            tree.setSort(productCategory.getProductCategorySort());
            list.add(tree);
        }
        TreeUtil treeUtil = new TreeUtil();
        List<Object> menuList = treeUtil.menuList(list);
        response.setCode(RetCode.SUCCESS);
        response.put("list", menuList);
        return response;
    }

    //查询三级分类优化
    @Override
    public Response getAllProductCategoryV2() {
        Response response = new Response();
        List<Tree> list = productCategoryDao.getAllProductCategoryV2();
        TreeUtil treeUtil = new TreeUtil();
        List<Object> menuList = treeUtil.menuList(list);
        response.setCode(RetCode.SUCCESS);
        response.put("list", menuList);
        return response;
    }

    @Override
    public Response getChildCategory(String pid) {
        Response response = new Response();
        List<ProductCategory> productCategories = productCategoryDao.getChildCategory(pid);
        response.setCode(RetCode.SUCCESS);
        response.put("list", productCategories);
        return response;
    }

    @Override
    public Response getSearchPropertyByCategory(String id) {

        Response response = new Response();
        //查询品牌
        List<Map<String, Object>> brands = productCategoryDao.getCategoryBrands(id);
        response.put("brands", brands);

        List<ProductProperty> productProperties = productPropertyDao.getProductPropertyByCategoryId(id);

        response.put("props", brands);

        //查询分类
        List<Map<String, Object>> propValues = productCategoryDao.getSearchPropertyByCategory(id);

        Map<String, List<Map<String, Object>>> propMap = new HashMap<>();

        for (ProductProperty productProperty : productProperties) {
            List<Map<String, Object>> list = getPropVals(productProperty.getPropertyId(), propValues);
            propMap.put(productProperty.getPropertyId(), list);
        }

        response.put("propMap", propMap);
        response.setCode(RetCode.SUCCESS);

        //高级搜索,查询上级分类
//        productCategoryMapper.getChildCategory()
        return response;
    }

    List<Map<String, Object>> getPropVals(String propertyId, List<Map<String, Object>> propValues) {
        List<Map<String, Object>> props = new ArrayList<>();
        for (Map<String, Object> map : propValues) {
            if (map.get("propertyId").equals(propertyId)) {
                props.add(map);
            }
        }
        return props;
    }

    @Override
    public Response getThirdCategoryByTopId(String id) {

        List<ProductCategory> list = productCategoryDao.getThirdCategoryByTopId(id);
        Response response = new Response();
        response.setCode(RetCode.SUCCESS);
        response.put("list", list);
        return response;
    }

}
